<template>
    <div class="storyContainer" ref="storyContainer">
        <div
            class="storySlideWrapper"
            :style="{ transform: `translateX(${totalOffset}px)`, transition: isTransitioning? 'transform 0.5s ease' : 'none' }"
            @mousedown="startDrag"
            @mousemove="onDrag"
            @mouseup="endDrag"
            @mouseleave="endDrag"
            @touchstart="startDrag"
            @touchmove="onDrag"
            @touchend="endDrag"
        >
            <div v-for="storyPage in storyPages" :key="storyPage.id" class="storySlide">
                <div class="topSection">
                    <div class="leftText">
                        <p v-html="storyPage.chapter"></p>
                        <h2 v-html="storyPage.title"></h2>
                    </div>
                    <div class="rightImage">
                        <img :src="storyPage.image" alt=""/>
                    </div>
                </div>
                <div class="bottomSection">
                    <div v-html="storyPage.leftText" class="bottomLeftText">
                    </div>
                    <div v-html="storyPage.rightText" class="bottomRightText">
                    </div>
                </div>
            </div>
        </div>
        <div class="paginationGroup">
      <span
          v-for="(_, pageIndex) in storyPages.length"
          :key="pageIndex"
          class="paginationDot"
          :class="{ active: pageIndex === currentPage }"
          @click="goToPage(pageIndex)"
      >
        <span class="dotBar"></span>
      </span>
        </div>
        <img v-show="!isFirstPage" class="prevPageBtn" src="/src/assets/img/common/carouselArrow.webp"
             @click="prevPage"/>
        <img v-show="!isLastPage" class="nextPageBtn" src="/src/assets/img/common/carouselArrow.webp"
             @click="nextPage"/>
    </div>
</template>

<script setup>
import {ref, computed} from 'vue';

const storyPages = ref([
    {
        id: '001',
        image: '/src/assets/img/careers/whyYou/storyBack01.webp',
        chapter: '<b>On the Job</b><br>part I',
        title: 'A Graphics Engineer\'s Story',
        leftText:
            '<p>What does the average day-to-day actually look like for an engineer, or for any other position, at Supercell? If you\'ve ever given a career with us some thought, you\'ve probably wondered about that. And for good reason, because there\'s only so much you can fit into an \'open positions\' notice of bearable length.</p>' +
            '<p>Of course, certain aspects of a job are universal. If you\'re an engineer, depending on your specialisation, you\'ll be designing databases, developing clients, churning out code and tinkering with curly brackets. That\'s just as true for Supercell as it is for other places.</p>' +
            '<p>What makes work at Supercell stand out is that whatever role you\'ve been hired for, you\'re in those shoes because...</p>' +
            '<ul><li>you\'re an expert at what you do</li><li>you don\'t hesitate to put that unique expertise of yours to use, and</li><li>you\'re committed to cooperation.</li></ul>',
        rightText:
            '<p>What we mean by applying your craft is probably self-explanatory, but what do we mean when we say we\'re looking for cooperative types? In practical terms, we\'re saying that your team\'s goals take precedence over personal agendas, that you\'re never too proud to ask questions, and that you appreciate the importance of helping others. Being friendly is essential, and an earnest respect for your team-mates and colleagues is indispensable.</p>' +
            '<p>Supercellians don\'t count years of tenure at the company when they choose who they listen to. You\'re trusted from day one to be a fully formed voice within your team and the company, contributing towards everyone\'s success.</p>' +
            '<p><i>Story continues on the next slide</i></p>',
    },
    {
        id: '002',
        image: '/src/assets/img/careers/whyYou/storyBack01.webp',
        chapter: '<b>On the Job</b><br>part I',
        title: 'A Graphics Engineer\'s Story',
        leftText:
            '<p>You won\'t be expected to conform to any corporate structures or layers, and you won\'t find any red tape even if you walk all the way down the office corridor. Having rigid formalities in place would make for a slightly more predictable organisation, but we optimise for speed. To that end, there\'s nothing like giving employees ownership over their work and the tools to operate with independence and speed.</p>' +
            '<p>A graphics engineer describes his early days at Supercell after joining the Tools & Tech team, who support our game development teams with the technology that they need:</p>' +
            '<p><i>When I joined the company, my team had already agreed with the game teams to build a new renderer for our games. I got to see what had been developed up to that point, and I was given the option to either keep it or rewrite it. What was already there looked really good and was a close match with how I would have approached the problem. So I picked it up from there.</i></p>',
        rightText:
            '<p><i>This was no small task, because to modify our games for the new renderer, I would have to get a feel for all the different game teams and their characteristic workflows. I started with Hay Day. Supercell\'s culture allowed me to collaborate with the Hay Day team directly, with minimal bureaucracy. Both my own team and the Hay Day crew all trusted me to make the necessary decisions to get the job done, and to handle all communications with the relevant parties first-hand. Whenever I needed a hand with something, everyone was always happy to help.</i></p>' +
            '<p><i>Having shipped the new renderer in Hay Day, I am now navigating the other game teams and making sure their code base works with the new renderer to eventually bring all games onboard. Without the culture that we have, building and implementing the new renderer would have been much more difficult and time consuming.</i></p>' +
            '<p><i>Read Part II on the next slide</i></p>',
    },
    {
        id: '003',
        image: '/src/assets/img/careers/whyYou/storyBack02.webp',
        chapter: '<b>On the Job</b><br>part II',
        title: 'An Artist\'s Story',
        leftText:
            '<p>Visitors on our careers page may have noticed that whenever we have an opening for an artist, we\'ve hardly ever had one for an Art Director . Well, sometimes we have, but we\'ve used quotation marks around the title: "Art Director". Because that is, and at the same time is not, what we are looking for.</p>' +
            '<p>Confused? Read on.</p>' +
            '<p>Supercell doesn\'t really have any junior artists on board, at all. Even the least experienced Supercellian artists will have a few notches in their belt and could easily call themselves "senior artists". Many are hardened industry veterans, the kind of people who would have been promoted past the daily grind of crafting art in most other companies, and into positions of directorship.</p>' +
            '<p>That hierarchical approach does not fit with how Supercell\'s artists operate, however. Here, an artist\'s experience is a tremendously valuable resource, but it\'s not a badge. Everyone who contributes to the artistic output of our company is essentially on an even footing and has an equally strong desire to work hands on.</p>' +
            '<p>People have their personal strengths and specialties, but nobody stands above anyone else. For that reason, it would be very misleading of us to give the impression that we are looking for art directors in a conventional sense.</p>',
        rightText:
            '<p>People have their personal strengths and specialties, but nobody stands above anyone else. For that reason, it would be very misleading of us to give the impression that we are looking for art directors in a conventional sense.</p>' +
            '<p>These values play in even when we turn to external production partners and freelancers to boost our ever-growing pipeline. One of our marketing artists, who has spent a lot of time with external studios on making animated videos for our games, sums it up like this:</p>' +
            '<p><i>Whenever I, together with fellow artist colleagues from Supercell, visit a studio for the first time, we\'re always cordially received by the studio heads, the CEO, the directors and the big-wheel producers. It goes without saying that we appreciate the gesture. It\'s an indication of how committed these partners are to helping us, and we want to show respect for the corporate culture that they have developed for their own purposes. Yet from the start of any of these partnerships, we always need to make sure that our partners understand one thing: that communicating solely with the managers isn\'t an option for us.</i></p>' +
            '<p><i>Story continues on next slide</i></p>',
    },
    {
        id: '004',
        image: '/src/assets/img/careers/whyYou/storyBack02.webp',
        chapter: '<b>On the Job</b><br>part II',
        title: 'An Artist\'s Story',
        leftText:
            '<p><i>What we\'ve noticed is that if we don\'t work directly with the artists themselves – meaning the very people who are doing the work that we\'re commissioning from them – we easily end up with results rather different from what we had in mind. This is only natural, because working through layers of management means things, even important things, may get lost in translation. This costs time and money, and can be demoralizing for everyone involved.</i></p>' +
            '<p><i>Talking to the artists without depending on proxies comes with two additional benefits. First of all, we get a much better understanding of how the studio actually goes about doing its work. With that information, it\'s much easier for us to formulate our requests. Besides, we then know where our assistance might be needed, and where our input might only be an unproductive distraction.</i></p>' +
            '<p><i>Secondly, an open connection between people is crucial for building trust. We want our partners to know who we are, and vice-versa. Sometimes, when we\'re working on projects to tight deadlines, there\'s a risk that everyone involved may end up doing an all-nighter to wrap up a project on time.</i></p>',
        rightText:
            '<p><i>We want those artists to know that they are doing it with us, as a temporary team of sorts on a collective effort, rather than having them feel that they are doing it just to keep their bosses happy. This shared sense of purpose has an incredible impact on the quality of the output.</i></p>' +
            '<p><i>The type of relationship described here is just as relevant within Supercell. Whatever you\'re working on is not something you\'re doing because your boss told you to do it, which is because their boss told them to deliver it. You\'re doing it for and with your team, because you and your colleagues have a mutual dedication to create something you can all be genuinely proud of.</i></p>',
    }
]);

const currentPage = ref(0);
const storyContainer = ref(null);
const dragStartX = ref(0);
const dragDelta = ref(0);
const totalOffset = ref(0);
const isDragging = ref(false);
const isTransitioning = ref(false);

const pageWidth = () => storyContainer.value?.clientWidth || 0;
const isFirstPage = computed(() => currentPage.value === 0);
const isLastPage = computed(() => currentPage.value === storyPages.value.length - 1);

const dragThreshold = 10;

const startDrag = (e) => {
    const target = e.target;
    if (target.closest('.storyTopLeft img')) return;

    isDragging.value = true;
    dragStartX.value = e.type.includes('mouse') ? e.clientX : e.touches[0].clientX;
    dragDelta.value = 0;
};

const onDrag = (e) => {
    if (!isDragging.value) return;
    const currentX = e.type.includes('mouse') ? e.clientX : e.touches[0].clientX;
    const delta = currentX - dragStartX.value;
    dragDelta.value = delta;
    totalOffset.value = -currentPage.value * pageWidth() + delta;
};

const endDrag = (e) => {
    if (!isDragging.value) return;
    isDragging.value = false;

    const endX = e.type.includes('mouse') ? e.clientX : e.changedTouches[0].clientX;
    const delta = endX - dragStartX.value;

    if (Math.abs(delta) < dragThreshold) {
        totalOffset.value = -currentPage.value * pageWidth();
        return;
    }

    if (delta > 100 && currentPage.value > 0) {
        currentPage.value--;
    } else if (delta < -100 && currentPage.value < storyPages.value.length - 1) {
        currentPage.value++;
    }

    isTransitioning.value = true;
    totalOffset.value = -currentPage.value * pageWidth();
    setTimeout(() => (isTransitioning.value = false), 500);
};

const prevPage = () => {
    if (isFirstPage.value) {
        bounce();
        return;
    }
    currentPage.value--;
    slideToCurrent();
};

const nextPage = () => {
    if (isLastPage.value) {
        bounce();
        return;
    }
    currentPage.value++;
    slideToCurrent();
};

const goToPage = (index) => {
    currentPage.value = index;
    slideToCurrent();
};

const slideToCurrent = () => {
    isTransitioning.value = true;
    totalOffset.value = -currentPage.value * pageWidth();
    setTimeout(() => (isTransitioning.value = false), 500);
};

const bounce = () => {
    isTransitioning.value = true;
    totalOffset.value += isFirstPage.value ? 50 : -50;
    setTimeout(() => {
        totalOffset.value = -currentPage.value * pageWidth();
        setTimeout(() => (isTransitioning.value = false), 300);
    }, 200);
};
</script>

<style scoped>
.storyContainer {
    position: relative;
    overflow: hidden;
    width: 100%;
    background-color: #000;
}

.storySlideWrapper {
    display: flex;
}

.storySlide {
    position: relative;
    flex: 0 0 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    cursor: default;
    color: #fff;
    user-select: none;
    -webkit-user-drag: none;
    height: 100%;
    padding: 80px 3%;
}

.topSection {
    display: flex;
    flex: 1;
    gap: 20px;
    justify-content: space-between;
}

.leftText {
    flex: 0 0 30%;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.leftText p {
    font-size: 22px;

}

.leftText h2 {
    text-transform: uppercase;
    font-size: 34px;
    margin-top: 45px;
}

.rightImage {
    flex: 0 0 66%;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.rightImage img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    -webkit-user-drag: none;
}

.bottomSection {
    display: flex;
    flex: 1;
    gap: 30px;
    justify-content: space-between;
    margin-top: 50px;
}


.bottomLeftText {
    flex: 1;
}

.bottomRightText {
    flex: 1;
}

:deep(.bottomLeftText p),
:deep(.bottomRightText p) {
    font-size: 18px;
    line-height: 1.6;
    margin-bottom: 30px;
}

:deep(.bottomLeftText ul) {
    font-size: 18px;
    height: 35px;
    line-height: 35px;
    padding: 0 50px;
    text-indent: 5px;
}

.prevPageBtn,
.nextPageBtn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 4%;
    cursor: pointer;
    z-index: 5;
    user-select: none;
    -webkit-user-drag: none;
    filter: invert(1);
    opacity: 0.5;
}

.prevPageBtn {
    left: 0;
}

.nextPageBtn {
    right: 0;
    transform: translateY(-50%) rotateY(180deg);
}

.paginationGroup {
    position: absolute;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 10px;
    z-index: 10;
}

.paginationDot {
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background-color: #ccc;
    cursor: pointer;
}

.paginationDot.active {
    background-color: #2d85f3;
    width: 24px;
    border-radius: 7px;
    transition: width 0.3s ease-in-out;
}
</style>